<?php
// +----------------------------------------------------------------------
// | 食得鲜 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.shidexian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 何锐 <poptser@foxmail.com>  [ ON THE WAY ]
// +----------------------------------------------------------------------
// | DateTime：2016-8-3 16:05:07
// +----------------------------------------------------------------------

namespace YMApi\Controller;
use Think\Controller;

//检查用户区域模块
//根据用户所在区域返回送货提交

class CheckregionController extends AppController
{
    public function _initialize($apptoken, $apptime)
    {
        parent::_initialize($apptoken, $apptime); // TODO: Change the autogenerated stub
    }

    /**
     *根据用户地址ID查询配送信息
     */
    public function check_serve_by_address_id(){
        $address_id = $_REQUEST['id'];
        if(is_numeric($address_id)){
            $address = $this->get_address_by_id($address_id);
            //dump($address);
            $address_gps = address_to_gps($address['all_address']);
            //dump($address_gps);
            //exit();
            $distribution_data = $this->get_distribution_by_gps($address_gps['longitude'],$address_gps['latitude']);
            //dump($distribution_data);
            if($distribution_data){
                $distribution_data['all_address'] = $address['all_address'];
                $distribution_data['lit_address'] = $address['lit_address'];
                $distribution_data['return'] =1;
            }else{
                $distribution_data['all_address'] = $address['all_address'];
                $distribution_data['lit_address'] = $address['lit_address'];
                $distribution_data['return'] =0;
            }
            returnApiSuccess($distribution_data);
        }else{
            returnApiError('参数错误');
        }



    }

    /**
     *根据经纬度坐标或者用户ID查询配送信息
     */
    public function check_serve_by_gps(){
        $latitude = $_REQUEST['lat_n'];     //大
        $longitude = $_REQUEST['lag_n'];    //小
        $user_id = $_REQUEST['user_id'];
        $hand = $_REQUEST['hand'];
        if($hand=="1"){
            $distribution_data = $this->get_distribution_by_gps($longitude,$latitude);
            //dump($latitude);
            //dump($longitude);
            //dump($distribution_data);
            $data = gps_to_address($longitude,$latitude);
            $distribution_data['all_address'] = $data['all_address'];
            $distribution_data['lit_address'] = $data['lit_address'];
        }else{
            $default_gps = $this->get_user_default_address_gps($user_id);
            if($default_gps){
                $distribution_data = $this->get_distribution_by_gps($default_gps['gps']['longitude'],$default_gps['gps']['latitude']);
                $distribution_data['all_address'] = $default_gps['all_address'];
                $distribution_data['lit_address'] = $default_gps['lit_address'];
            }else{
                $distribution_data = $this->get_distribution_by_gps($longitude,$latitude);
                $data = gps_to_address($longitude,$latitude);
                $distribution_data['all_address'] = $data['all_address'];
                $distribution_data['lit_address'] = $data['lit_address'];
            }
        }
        if($distribution_data){

            $distribution_data['return'] =1;
        }else{
            $distribution_data['return'] =0;
        }
        returnApiSuccess($distribution_data);

    }



    /**
     * 根据ID查询详细地址
     * Author:何锐 <poptser@foxmail.com>
     * @param $address_id
     * @return bool|string
     */
    public function get_address_by_id($address_id){
        $user_address = M("user_address")->where('address_id ='.$address_id)->order('province,city,district,address')->find();
        if($user_address){
            $province = M('region')->where('region_id ='.$user_address['province'])->getField('region_name');
            $city = M('region')->where('region_id ='.$user_address['city'])->getField('region_name');
            $district = M('region')->where('region_id ='.$user_address['district'])->getField('region_name');
            $all_address = $province.$city.$district.$user_address['address'].$user_address['sign_building'];
            $data['all_address'] = str_replace(' ','',$all_address);
            $data['lit_address'] = $user_address['sign_building'];
            return $data;
        }else{
            return false;
        }
    }



    /**
     * 获取用户默认地址的GPS坐标值
     * Author:何锐 <poptser@foxmail.com>
     * @param $uid
     * @return bool|void
     */
    public function get_user_default_address_gps($uid){
        $where['user_id'] = $uid;
        $where['default'] = 1;
        $user_address_id = M("user_address")->where($where)->getField('address_id');
        if ($user_address_id){
            $data = $this->get_address_by_id($user_address_id);
            $data['gps'] = address_to_gps($data['all_address']);
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 根据经纬度获取区域优惠信息
     * @param $longitude
     * @param $latitude
     */
    public function get_distribution_by_gps($longitude, $latitude){
        $wdr_mod=M('warehouse_deliver_region');
        $wdrc_mod=M('warehouse_deliver_region_coordinates');
        $wdr=$wdr_mod->where(array('status'=>1))->select();
        if($wdr){
            $polygon_free='';
            $polygon_99_top='';
            $polygon_99_bottom='';
            $polygon_199='';
            $polygon_69='';
            $polygon_299='';
            $polygon_39='';
            $polygon_39_c='';
            $polygon_399='';
            foreach ($wdr as $key=>$val){
                if($val['wdtype']==0){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_free[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==1){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_99_top[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>(float)$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==2){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){

                            $polygon_99_bottom[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==3){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_199[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==4){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_69[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==5){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_299[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==6){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_39[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==7){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_399[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }elseif($val['wdtype']==8){
                    $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                    if ($wdrc){
                        foreach ($wdrc as $k=>$v){
                            $polygon_39_c[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                        }
                    }else {
                        continue;
                    }
                }
            }
        }else{
            return false;
        }
        if($polygon_free){
            foreach ($polygon_free as $key=>$val){
                foreach ($val as $k=>$v){
                    $free[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($free,$longitude,$latitude);
                if($data){
                    $arr['price'] = (float)$free[0]['start_price'];
                    $arr['name'] = "free";
                    $arr['prescription'] = "3小时";
                    $arr['wid']=$free[0]['wid'];
                    $arr['is_day']=0;
                    return $arr;
                }
                unset($free);
                unset($data);
            }
        }
        if($polygon_99_top){
            foreach ($polygon_99_top as $key=>$val){
                foreach ($val as $k=>$v){
                    $top[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($top,$longitude,$latitude);
                if($data){
                    $arr['name'] = "99";
                    $arr['price'] = (float)$top[0]['start_price'];
                    $arr['prescription'] = "24小时";
                    $arr['wid']=$top[0]['wid'];
                    $arr['is_day']=1;
                    return $arr;
                }
                unset($top);
                unset($data);
            }
        }
        if($polygon_99_bottom){
            foreach ($polygon_99_bottom as $key=>$val){
                foreach ($val as $k=>$v){
                    $bottom[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($bottom,$longitude,$latitude);
                if($data){
                    $arr['name'] = "99";
                    $arr['price'] = (float)$bottom[0]['start_price'];
                    $arr['prescription'] = "24小时";
                    $arr['wid']=$bottom[0]['wid'];
                    $arr['is_day']=1;
                    return $arr;
                }
                unset($bottom);
                unset($data);
            }
        }
        if($polygon_199){
            foreach ($polygon_199 as $key=>$val){
                foreach ($val as $k=>$v){
                    $p199[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($p199,$longitude,$latitude);
                if($data){
                    $arr['name'] = "199";
                    $arr['price'] = (float)$p199[0]['start_price'];
                    $arr['prescription'] = "24小时";
                    $arr['wid']=$p199[0]['wid'];
                    $arr['is_day']=1;
                    return $arr;
                }
                unset($p199);
                unset($data);
            }
        }
        if($polygon_69){
            foreach ($polygon_69 as $key=>$val){
                foreach ($val as $k=>$v){
                    $p69[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($p69,$longitude,$latitude);
                if($data){
                    $arr['name'] = "69";
                    $arr['price'] = (float)$p69[0]['start_price'];
                    $arr['prescription'] = "3小时";
                    $arr['wid']=$p69[0]['wid'];
                    $arr['is_day']=0;
                    return $arr;
                }
                unset($p69);
                unset($data);
            }
        }
        if($polygon_299){
            foreach ($polygon_299 as $key=>$val){
                foreach ($val as $k=>$v){
                    $p299[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($p299,$longitude,$latitude);
                if($data){
                    $arr['name'] = "299";
                    $arr['price'] = (float)$p299[0]['start_price'];
                    $arr['prescription'] = "24小时";
                    $arr['wid']=$p299[0]['wid'];
                    $arr['is_day']=1;
                    return $arr;
                }
                unset($p299);
                unset($data);
            }
        }
        if($polygon_39){
            foreach ($polygon_39 as $key=>$val){
                foreach ($val as $k=>$v){
                    $p39[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($p39,$longitude,$latitude);
                if($data){
                    $arr['name'] = "39";
                    $arr['price'] = (float)$p39[0]['start_price'];
                    $arr['prescription'] = "3小时";
                    $arr['wid']=$p39[0]['wid'];
                    $arr['is_day']=0;
                    return $arr;
                }
                unset($p39);
                unset($data);
            }
        }
        if($polygon_39_c){
            foreach ($polygon_39_c as $key=>$val){
                foreach ($val as $k=>$v){
                    $p39_c[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($p39_c,$longitude,$latitude);
                if($data){
                    $arr['name'] = "39";
                    $arr['price'] = (float)$p39_c[0]['start_price'];
                    $arr['prescription'] = "24小时";
                    $arr['wid']=$p39_c[0]['wid'];
                    $arr['is_day']=1;
                    return $arr;
                }
                unset($p39_c);
                unset($data);
            }
        }
        if($polygon_399){
            foreach ($polygon_399 as $key=>$val){
                foreach ($val as $k=>$v){
                    $p399[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($p399,$longitude,$latitude);
                if($data){
                    $arr['name'] = "399";
                    $arr['price'] = (float)$p399[0]['start_price'];
                    $arr['prescription'] = "24小时";
                    $arr['wid']=$p399[0]['wid'];
                    $arr['is_day']=1;
                    return $arr;
                }
                unset($p399);
                unset($data);
            }
        }
        return false;
    }

/**
     * 射线法计算坐标是否在规定图形内
     * @param $polygon
     * @param $longitude
     * @param $latitude
     * @return bool
     */
    /* private function isPointInPolygon($polygon, $longitude, $latitude){
        $count = count($polygon);
        $px = $longitude;
        $py = $latitude;
        $flag = false;
        for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
            $sy = $polygon[$i]['lng'];
            $sx = $polygon[$i]['lat'];
            $ty = $polygon[$j]['lng'];
            $tx = $polygon[$j]['lat'];
            $wid=$polygon[$i]['wid'];
             $wdr_id=$polygon[$i]['wdr_id'];
             $name=$polygon[$i]['name'];
             $price=$polygon[$i]['start_price'];
             $data=array('wid'=>$wid,'wdr_id'=>$wdr_id,'qyname'=>$name,'price'=>$price);
            if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
            {   
            return $data;
            }
            if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
                $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
                if ($x == $px){
                    return $data;
                }
                if ($x > $px){
                    //$flag = !$flag;
                    return $data;
                }
                    
            }
        }
       
        return $flag;
    }*/
    

    /**
     * 射线法计算坐标是否在规定图形内
     * @param $polygon
     * @param $longitude
     * @param $latitude
     * @return bool
     */
    private function isPointInPolygon($polygon, $longitude, $latitude){
        $count = count($polygon);
        $px = $longitude;
        $py = $latitude;
        $flag = false;
        for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
            $sy = $polygon[$i]['lng'];
            $sx = $polygon[$i]['lat'];
            $ty = $polygon[$j]['lng'];
            $tx = $polygon[$j]['lat'];
            if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
            {
                return true;
            }
            if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
                $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
                if ($x == $px){
                    return true;
                }
                if ($x > $px){
                    $flag = !$flag;
                }
    
            }
        }
        return $flag;
    }

	/**
	 *地址自动提示补全
     */
	public function auto_address_complete(){
		$keyword= $page_num = I("post.key");

		$key_array = array(
			"RFDBZ-BJL3F-463JB-J5VHW-Z2QDV-GQFV6",      //50W次KEY
			"RROBZ-OUFKP-RSKDT-LPEF7-GPWMK-IKFZF",
			"DECBZ-36DRG-CQQQY-IIRZV-LADUF-EGBNG",
			"4GJBZ-MWRRX-JPV4H-TOTTS-4RLVS-RABIX",
			"NQ5BZ-HEE3X-D3D4L-7NLSA-G4GPT-QXFHZ",
			"NYLBZ-NLS3X-VRZ4F-ZK7XB-46UT7-KOBNC",
			"I6MBZ-YYPWU-U66V3-B2J2P-WGCNO-4WBZ5",
			"HG3BZ-UOAHR-QLMWE-WJRVM-6Z337-OCBZN",
			"EAFBZ-772RX-ADQ4F-Z3SVS-BCUZ2-A6BLU",
			"VYIBZ-E56RP-I44DP-VJUD3-MSZ5Q-IJFQF",
			"26MBZ-FN3RP-U2DDA-VF6XQ-CZA5S-ZXFNZ",
		);

		foreach ($key_array as $key=>$value){
			$url = "http://apis.map.qq.com/ws/place/v1/suggestion/?keyword=".$keyword."&key=".$value."&get_poi=1&region=广州&policy=1";
			$html = file_get_contents($url);
			$data = json_decode($html,true);
			if($data['status']==0){
				$data['data'] = $this->convertdata($data['data']);
				$data['json'] = $html;
				returnApiSuccess($data);
				break;
				exit();
			}
		}
		returnApiError('fail');
	}
	
	/*
	 * 转换处理详细地址
	 */
	private function convertdata($data){
		if(!empty($data)){
			foreach ($data  as $key=>$val){
// 				if(strpos($data[$key]['address'],$val['title'])===false){
// 					$data[$key]['address'] =$data[$key]['address'].$val['title'];
// 				}
				if(strpos($data[$key]['address'],$val['district'])===false){
					$data[$key]['address'] =$val['district'].$data[$key]['address'];
				}
				if(strpos($data[$key]['address'],$val['city'])===false){
					$data[$key]['address'] =$val['city'].$data[$key]['address'];
				}
				if(strpos($data[$key]['address'],$val['province'])===false){
					$data[$key]['address'] =$val['province'].$data[$key]['address'];
				}
			}
		}
		return $data;
	}
}